package lib.Com;

import java.net.*;
import java.io.*;

public class PublicIPAddress {
	/**
	 * Class to get the public ip address.
	 */
	private static String ip = null;
	
	public static String getPublicIPAddress(){
		if(ip != null){
			return ip;
		}else{
			ip = makeUrlConnection();
			return ip;
		}
	}
	
	private static String makeUrlConnection() {
		
		//URL publicIPService1;
		URL publicIPService2;
		URL publicIPService3;
		
		try{
			//publicIPService1 = new URL("http://automation.whatismyip.com/n09230945.asp"); --old and abandoned ip
			publicIPService2 = new URL("http://gt-tests.appspot.com/ip");
			publicIPService3 = new URL("http://checkip.dyndns.com/");
		}catch(MalformedURLException ex){
			ex.printStackTrace();
			return "";
		}

	    URLConnection connection;
	    
	    try{
	    	//connection = publicIPService1.openConnection();
	    	connection = publicIPService2.openConnection();
		}catch(IOException ex1){
			try{
				connection = publicIPService3.openConnection();
			}catch(IOException ex2){
				ex2.printStackTrace();
				return "";
			}
		}
	    
		//Setting up header information
		connection.addRequestProperty("Protocol", "Http/1.1");
	    connection.addRequestProperty("Connection", "keep-alive");
	    connection.addRequestProperty("Keep-Alive", "1000");
	    connection.addRequestProperty("User-Agent", "Web-Agent");
	    
	    try{
	    	BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	    	
	    	String[] ip = in.readLine().split(":");
	    	
	    	ip = ip[ip.length-1].split("<");
	    	
	    	return ip[0].trim();
			
		}catch(IOException ex){
			return "";
		}
	}
}